package com.zzyl.serve.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.serve.domain.NursingProjectPlan;
import com.zzyl.serve.dto.NursingPlanDto;
import com.zzyl.serve.service.INursingProjectPlanService;
import com.zzyl.serve.service.INursingProjectService;
import com.zzyl.serve.vo.NursingPlanVo;
import com.zzyl.serve.vo.NursingProjectPlanVo;
import com.zzyl.serve.vo.NursingProjectVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.NursingPlanMapper;
import com.zzyl.serve.domain.NursingPlan;
import com.zzyl.serve.service.INursingPlanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 护理计划Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-04
 */
@Service
@Slf4j
public class NursingPlanServiceImpl extends ServiceImpl<NursingPlanMapper, NursingPlan> implements INursingPlanService {
    @Autowired
    private NursingPlanMapper nursingPlanMapper;
    @Autowired
    private INursingProjectPlanService iNursingProjectPlanService;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    // 常量:缓存的key-全查护理计划表
    private static final String CACHE_KEY_NURSING_PLAN_ALL = "nursingPlan:all";

    /**
     * 查询护理计划
     *
     * @param id 护理计划主键
     * @return 护理计划
     */
    @Override
    public NursingPlanVo selectNursingPlanById(Long id) {
//        // 创建返回的结果
//        NursingPlanVo result1 = new NursingPlanVo();
//        // 查计划表和中间表
//        NursingPlan nursingPlan = this.getById(id);
//        BeanUtils.copyProperties(nursingPlan, result1);
//
//        List<NursingProjectPlan> nursingProjectPlans = iNursingProjectPlanService.list(Wrappers.<NursingProjectPlan>lambdaQuery().eq(NursingProjectPlan::getPlanId, id));
//        // 将projectPlans转换成projectPlanVos
//        List<NursingProjectPlanVo> nursingProjectPlanVos = nursingProjectPlans.stream().map(nursingProjectPlan -> {
//            NursingProjectPlanVo nursingProjectPlanVo = new NursingProjectPlanVo();
//            nursingProjectPlanVo.setProjectId(nursingProjectPlan.getProjectId().toString());
//            nursingProjectPlanVo.setId(nursingProjectPlan.getId());
//            nursingProjectPlanVo.setPlanId(nursingProjectPlan.getPlanId());
//            nursingProjectPlanVo.setExecuteCycle(nursingProjectPlan.getExecuteCycle().toString());
//            nursingProjectPlanVo.setExecuteTime(nursingProjectPlan.getExecuteTime());
//            nursingProjectPlanVo.setExecuteFrequency(nursingProjectPlan.getExecuteFrequency());
//            return nursingProjectPlanVo;
//        }).toList();
//        result1.setProjectPlans(nursingProjectPlanVos);

        NursingPlanVo result = nursingPlanMapper.selectNursingPlanById(id);
//        log.warn("================> result:{}",result);
        return result;

    }

    /**
     * 查询护理计划列表
     *
     * @param nursingPlan 护理计划
     * @return 护理计划
     */
    @Override
    public List<NursingPlan> selectNursingPlanList(NursingPlan nursingPlan) {
        return nursingPlanMapper.selectNursingPlanList(nursingPlan);
    }

    /**
     * 新增护理计划
     *
     * @param
     * @return 结果
     */
    @Override
    @Transactional
    public int insertNursingPlan(NursingPlanDto dto) {
        // return nursingPlanMapper.insertNursingPlan(nursingPlan);
        // 保存护理计划
        NursingPlan nursingPlan = new NursingPlan();
        // 利用BeanUtils工具类将dto中的属性复制给nursingPlan
        // 要求:两个对象的属性名以及类型必须完全一致,才可以拷贝
        BeanUtils.copyProperties(dto, nursingPlan);
//        nursingPlanMapper.insertNursingPlan(nursingPlan);
        this.save(nursingPlan);

        // 批量保存护理项目计划关系
        // 使用mabatis,自己手写的批量添加方法
//        int count = nursingProjectPlanMapper.batchInsert(dto.getProjectPlans(), nursingPlan.getId());
        // 使用mp提供的批量添加方法
        List<NursingProjectPlan> projectPlans = dto.getProjectPlans();
        // 给projectPlans中的项目计划设置计划id
        if (!CollectionUtils.isEmpty(projectPlans)) {
            projectPlans.forEach(projectPlan -> {
                projectPlan.setPlanId(nursingPlan.getId());
            });
        }
        boolean result = iNursingProjectPlanService.saveBatch(projectPlans);
        // 最后删缓存
        redisTemplate.delete(CACHE_KEY_NURSING_PLAN_ALL);
        return result ? 1 : 0;
    }

    /**
     * 修改护理计划
     *
     * @param
     * @return 结果
     */
    @Override
    @Transactional
    public int updateNursingPlan(NursingPlanDto nursingPlanDto) {
        // 先修改中间表
        List<NursingProjectPlan> projectPlans = nursingPlanDto.getProjectPlans();
        if (!CollectionUtils.isEmpty(projectPlans)) {
            // 中间表如果不为空,先全删再添加
            iNursingProjectPlanService.remove(Wrappers.<NursingProjectPlan>lambdaQuery().eq(NursingProjectPlan::getPlanId, nursingPlanDto.getId()));
            iNursingProjectPlanService.saveBatch(projectPlans);
        }
        // 修改计划表
        NursingPlan nursingPlan = new NursingPlan();
        BeanUtils.copyProperties(nursingPlanDto, nursingPlan);
        boolean result = this.updateById(nursingPlan);
        // 最后删缓存
        redisTemplate.delete(CACHE_KEY_NURSING_PLAN_ALL);
        return result ? 1 : 0;
    }

    /**
     * 批量删除护理计划
     *
     * @param ids 需要删除的护理计划主键
     * @return 结果
     */
    @Override
    public int deleteNursingPlanByIds(Long[] ids) {
        // 先判断状态是否为启用,为启用不能删
        List<NursingPlan> nursingPlans = this.listByIds(Arrays.stream(ids).collect(Collectors.toList()));
        if (!CollectionUtils.isEmpty(nursingPlans)) {
            nursingPlans.forEach(nursingPlan -> {
                if (nursingPlan.getStatus() == 1) {
                    throw new RuntimeException("启用的护理计划不能删除!");
                }
            });
        }
        // 先删中间表
        iNursingProjectPlanService.remove(Wrappers.<NursingProjectPlan>lambdaQuery().in(NursingProjectPlan::getPlanId, ids));
        // 再删计划表
        boolean result = this.removeByIds(Arrays.stream(ids).collect(Collectors.toList()));
        // 最后删缓存
        redisTemplate.delete(CACHE_KEY_NURSING_PLAN_ALL);
        return result ? 1 : 0;
    }

    /**
     * 查询所有护理计划
     *
     * @return 列表
     */
    @Override
    public List<NursingPlan> listAll() {
        // 先查缓存
        List<NursingPlan> result = (List<NursingPlan>) redisTemplate.opsForValue().get(CACHE_KEY_NURSING_PLAN_ALL);
        // 缓存中有直接返回
        if (!CollectionUtils.isEmpty(result)) {
            return result;
        }
        // 缓存中没有,查数据库,并给缓存赋值
        result = this.list(Wrappers.<NursingPlan>lambdaQuery().eq(NursingPlan::getStatus, 1));
        redisTemplate.opsForValue().set(CACHE_KEY_NURSING_PLAN_ALL, result);
        return result;
    }

    /**
     * 删除护理计划信息
     *
     * @param id 护理计划主键
     * @return 结果
     */
//    @Override
//    public int deleteNursingPlanById(Long id) {
//        return removeById(id) ? 1 : 0;
//    }
}
